<template>
  <div class="login">
    <Particles id="tsparticles" class="login__particles" :options="options" />

    <div class="loginPart">
      <h2>用户登录</h2>
      <el-form :model="loginForm" ref="loginFormRef" :rules="rules" label-width="100px"
        style="transform: translate(-30px)" @keyup.enter="handleLogin">
        <el-form-item label="账号" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password clearable></el-input>
        </el-form-item>

        <el-button class="btn" type="primary" :loading="isLoading" @click="handleLogin" >
          登录
        </el-button>
        <div class="link-container">
          <el-link type="danger" @click.prevent="changeUrl('/forget')">
            忘记密码？
          </el-link>
          <el-link type="warning" @click.prevent="changeUrl('/register')">
            没有账号？去注册
          </el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "@/utils/http"; // 确保已正确配置 Axios 工具文件
import '../components/UserLogin.scss'

// 表单数据
const loginForm = reactive({
  username: "admin",
  password: "000000",
});

// 表单引用
const loginFormRef = ref(null);

// 表单验证规则
const rules = {
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        // 自定义验证逻辑：账号必须是2-6位的中文、数字或字母组合
        const usernamePattern = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,6}$/;
        if (!value || usernamePattern.test(value)) {
          callback(); // 验证通过
        } else {
          callback(new Error("账号格式不正确（2-6位的中文、数字或字母组合）"));
        }
      },
      trigger: ["blur", "change"],
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应在6到20个字符之间", trigger: "blur" },
  ],
};

// 路由实例
const router = useRouter();

// 加载状态
const isLoading = ref(false);

// 登录逻辑
import qs from 'qs'; // 安装 qs 库以处理 URL 编码

const handleLogin = async () => {
  try {
    isLoading.value = true;

    // 表单校验
    await loginFormRef.value.validate((valid) => {
      if (valid) {
        // 将字段名映射为后端期望的格式
        const requestData = {
          username: loginForm.username,
          password: loginForm.password,
        };

        // 使用 qs.stringify 将数据转换为 URL 编码格式
        axios
          .post(
            "/login/",
            qs.stringify(requestData),
            { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
          )
          .then((res) => {
            // console.log("登录成功:", res);
            if (res.data.code === 200) {
              ElMessage.success("登录成功");
              window.sessionStorage.setItem("token", res.data.data.token);
              window.sessionStorage.setItem("userInfo", JSON.stringify(res.data.data));
              // 直接存储权限数组
              window.sessionStorage.setItem("permissions", JSON.stringify(res.data.data.functions));
              router.push("/home");
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .catch((error) => {
            console.error("登录失败:", error);
            ElMessage.error("网络错误！");
          })
          .finally(() => {
            isLoading.value = false; // 确保加载状态重置
          });
      } else {
        isLoading.value = false; // 校验失败时重置加载状态
      }
    });
  } catch (error) {
    console.error("表单校验失败:", error);
    isLoading.value = false; // 校验失败时重置加载状态
  }
};

// 跳转路由
const changeUrl = (url) => {
  router.push(url); // 使用 push 方法代替 replace
  console.log("跳转路由:", url);
};

// 粒子效果配置
const options = {
  fpsLimit: 60,
  interactivity: {
    detectsOn: "canvas",
    events: {
      onClick: {
        enable: true,
        mode: "push",
      },
      onHover: {
        enable: true,
        mode: "grab",
      },
      resize: true,
    },
    modes: {
      bubble: {
        distance: 400,
        duration: 2,
        opacity: 0.8,
        size: 40,
      },
      push: {
        quantity: 4,
      },
      grab: {
        distance: 200,
        duration: 0.4,
      },
      attract: {
        distance: 200,
        duration: 0.4,
        factor: 5,
      },
    },
  },
  particles: {
    color: {
      value: "#BA55D3", // 粒子点的颜色
    },
    links: {
      color: "#FFBBFF", // 线条颜色
      distance: 150, // 线条距离
      enable: true,
      opacity: 0.4, // 不透明度
      width: 1.2, // 线条宽度
    },
    collisions: {
      enable: true,
    },
    move: {
      attract: { enable: false, rotateX: 600, rotateY: 1200 },
      bounce: false,
      direction: "none",
      enable: true,
      out_mode: "out",
      random: false,
      speed: 0.5, // 移动速度
      straight: false,
    },
    number: {
      density: {
        enable: true,
        value_area: 800,
      },
      value: 80, // 粒子数
    },
    opacity: {
      value: 0.7,
    },
    shape: {
      type: "star",
    },
    size: {
      random: true,
      value: 3,
    },
  },
  detectRetina: true,
};
</script>
